package com.hospital.dictionary.module.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hospital.common.core.result.ErrorTip;
import com.hospital.common.core.result.SuccessTip;
import com.hospital.common.core.result.Tip;
import com.hospital.dictionary.common.DictModel;
import com.hospital.dictionary.constant.CommonConstant;
import com.hospital.dictionary.module.controller.dto.SysDictTree;
import com.hospital.dictionary.module.entity.SysDict;
import com.hospital.dictionary.module.service.SysDictService;
import com.hospital.dictionary.query.QueryGenerator;
import com.hospital.dictionary.utils.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/module/dict")
public class SysDictController {
    @Autowired
    private SysDictService sysDictService;



    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Tip queryPageList(SysDict sysDict, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                             @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        QueryWrapper<SysDict> queryWrapper = QueryGenerator.initQueryWrapper(sysDict, req.getParameterMap());
        Page<SysDict> page = new Page<SysDict>(pageNo, pageSize);
        IPage<SysDict> pageList = sysDictService.page(page, queryWrapper);
        return new SuccessTip(pageList);
    }



    /**
     * @功能：获取树形字典数据
     * @param sysDict
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/treeList", method = RequestMethod.GET)
    public Tip treeList(SysDict sysDict, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        LambdaQueryWrapper<SysDict> query = new LambdaQueryWrapper<>();
        // 构造查询条件
        String dictName = sysDict.getDictName();
        if(oConvertUtils.isNotEmpty(dictName)) {
            query.like(true, SysDict::getDictName, dictName);
        }
        query.orderByDesc(true, SysDict::getCreateTime);
        List<SysDict> list = sysDictService.list(query);
        List<SysDictTree> treeList = new ArrayList<>();
        for (SysDict node : list) {
            treeList.add(new SysDictTree(node));
        }
        return new SuccessTip(treeList);
    }


    /**
     * 获取全部字典数据
     *
     * @return
     */
    @RequestMapping(value = "/queryAllDictItems", method = RequestMethod.GET)
    public Tip queryAllDictItems(HttpServletRequest request) {
        Map<String, List<DictModel>> res = new HashMap<String, List<DictModel>>();
        res = sysDictService.queryAllDictItems();
        return new SuccessTip(res);
    }

    /**
     * 获取字典数据
     * @param dictCode
     * @return
     */
    @RequestMapping(value = "/getDictText/{dictCode}/{key}", method = RequestMethod.GET)
    public Tip getDictText(@PathVariable("dictCode") String dictCode, @PathVariable("key") String key) {
        String text = null;
        try {
            text = sysDictService.queryDictTextByKey(dictCode, key);
        } catch (Exception e) {
            return new ErrorTip(501,"操作失败");
        }
        return new SuccessTip(text);
    }

    /**
     * @功能：新增
     * @param sysDict
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Tip add(@RequestBody SysDict sysDict) {
        try {
            sysDict.setCreateTime(new Date());
            sysDict.setDelFlag(CommonConstant.DEL_FLAG_0);
            sysDictService.save(sysDict);
            int tableExist = sysDictService.isTableExist(sysDict.getTableName());
            if(tableExist<=0){
                sysDictService.createTable(sysDict.getTableName());
            }
            return new SuccessTip("操作成功");
        } catch (Exception e) {
            return new ErrorTip(302,"操作失败");
        }
    }

    /**
     * @功能：编辑
     * @param sysDict
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Tip edit(@RequestBody SysDict sysDict) {
        SysDict sysdict = sysDictService.getById(sysDict.getId());
        if(sysdict==null) {
           return new ErrorTip(500,"未找到对应实体类");
        }else {
            sysDict.setUpdateTime(new Date());
            boolean ok = sysDictService.updateById(sysDict);
            int tableExist = sysDictService.isTableExist(sysDict.getTableName());
            if(tableExist<=0){
                sysDictService.createTable(sysDict.getTableName());
            }
            if(ok) {
               return new SuccessTip("操作成功");
            }else {
                return new ErrorTip(302,"操作失败");
            }
        }
    }

    /**
     * @功能：删除
     * @param id
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Tip delete(@RequestParam(name="id",required=true) String id) {
        boolean ok = sysDictService.removeById(id);
        if(ok) {
            return new SuccessTip("操作成功");
        }else{
           return new ErrorTip(302,"操作失败");
        }
    }

    /**
     * @功能：批量删除
     * @param ids
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Tip deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        if(oConvertUtils.isEmpty(ids)) {
            return new ErrorTip(500,"参数不识别");
        }else {
            sysDictService.removeByIds(Arrays.asList(ids.split(",")));
            return new SuccessTip("操作成功");
        }
    }

//    /**
//     * @功能：刷新缓存
//     * @return
//     */
//    @RequestMapping(value = "/refleshCache")
//    public Result<?> refleshCache() {
//        Result<?> result = new Result<SysDict>();
//        //清空字典缓存
//        Set keys = redisTemplate.keys(CacheConstant.SYS_DICT_CACHE + "*");
//        Set keys2 = redisTemplate.keys(CacheConstant.SYS_DICT_TABLE_CACHE + "*");
//        Set keys3 = redisTemplate.keys(CacheConstant.SYS_DEPARTS_CACHE + "*");
//        Set keys4 = redisTemplate.keys(CacheConstant.SYS_DEPART_IDS_CACHE + "*");
//        redisTemplate.delete(keys);
//        redisTemplate.delete(keys2);
//        redisTemplate.delete(keys3);
//        redisTemplate.delete(keys4);
//        return result;
//    }

//    /**
//     * 导出excel
//     *
//     * @param request
//     */
//    @RequestMapping(value = "/exportXls")
//    public ModelAndView exportXls(SysDict sysDict, HttpServletRequest request) {
//        // Step.1 组装查询条件
//        QueryWrapper<SysDict> queryWrapper = QueryGenerator.initQueryWrapper(sysDict, request.getParameterMap());
//        //Step.2 AutoPoi 导出Excel
//        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//        List<SysDictPage> pageList = new ArrayList<SysDictPage>();
//
//        List<SysDict> sysDictList = sysDictService.list(queryWrapper);
//        for (SysDict dictMain : sysDictList) {
//            SysDictPage vo = new SysDictPage();
//            BeanUtils.copyProperties(dictMain, vo);
//            // 查询机票
//            List<SysDictItem> sysDictItemList = sysDictItemService.selectItemsByMainId(dictMain.getId());
//            vo.setSysDictItemList(sysDictItemList);
//            pageList.add(vo);
//        }
//
//        // 导出文件名称
//        mv.addObject(NormalExcelConstants.FILE_NAME, "数据字典");
//        // 注解对象Class
//        mv.addObject(NormalExcelConstants.CLASS, SysDictPage.class);
//        // 自定义表格参数
//        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("数据字典列表", "导出人:"+user.getRealname(), "数据字典"));
//        // 导出数据列表
//        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
//        return mv;
//    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
//            MultipartFile file = entity.getValue();// 获取上传文件对象
//            ImportParams params = new ImportParams();
//            params.setTitleRows(2);
//            params.setHeadRows(2);
//            params.setNeedSave(true);
//            try {
//                //update-begin-author:wangshuai date:20201030 for:导入测试用例
//                boolean aBoolean = FieldPresenceUtil.fieldPresence(file.getInputStream(), SysDictPage.class, params);
//                if(!aBoolean){
//                    throw  new RuntimeException("导入Excel标题格式不匹配！");
//                }
//                //update-end-author:wangshuai date:20201030 for:导入测试用例
//                List<SysDictPage> list = ExcelImportUtil.importExcel(file.getInputStream(), SysDictPage.class, params);
//                // 错误信息
//                List<String> errorMessage = new ArrayList<>();
//                int successLines = 0, errorLines = 0;
//                for (int i=0;i< list.size();i++) {
//                    SysDict po = new SysDict();
//                    BeanUtils.copyProperties(list.get(i), po);
//                    po.setDelFlag(CommonConstant.DEL_FLAG_0);
//                    try {
//                        Integer integer = sysDictService.saveMain(po, list.get(i).getSysDictItemList());
//                        if(integer>0){
//                            successLines++;
//                        }else{
//                            errorLines++;
//                            int lineNumber = i + 1;
//                            errorMessage.add("第 " + lineNumber + " 行：字典编码已经存在，忽略导入。");
//                        }
//                    }  catch (Exception e) {
//                        errorLines++;
//                        int lineNumber = i + 1;
//                        errorMessage.add("第 " + lineNumber + " 行：字典编码已经存在，忽略导入。");
//                    }
//                }
//                return ImportExcelUtil.imporReturnRes(errorLines,successLines,errorMessage);
//            } catch (Exception e) {
//                log.error(e.getMessage(),e);
//                return Result.error("文件导入失败:"+e.getMessage());
//            } finally {
//                try {
//                    file.getInputStream().close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return Result.error("文件导入失败！");
//    }


    /**
     * 查询被删除的列表
     * @return
     */
    @RequestMapping(value = "/deleteList", method = RequestMethod.GET)
    public Tip deleteList() {
        List<SysDict> list = this.sysDictService.queryDeleteList();
        return new SuccessTip(list);
    }

    /**
     * 物理删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/deletePhysic/{id}", method = RequestMethod.DELETE)
    public Tip deletePhysic(@PathVariable String id) {
        try {
            sysDictService.deleteOneDictPhysically(id);
            return new SuccessTip("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorTip(302,"操作失败");
        }
    }

    /**
     * 取回
     * @param id
     * @return
     */
    @RequestMapping(value = "/back/{id}", method = RequestMethod.PUT)
    public Tip back(@PathVariable String id) {
        try {
            sysDictService.updateDictDelFlag(0,id);
            return new SuccessTip("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorTip(302,"操作失败!");
        }
    }
}
